package com.tanhua.admin.controller;

import cn.hutool.Hutool;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.tanhua.admin.service.AdminService;
import com.tanhua.commons.utils.Constants;
import com.tanhua.model.db.Admin;
import com.tanhua.model.vo.AdminVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/system/users")
public class SystemController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/verification")  //发送验证码  手机端用手机号做key保证唯一性，后台用uuid保证唯一性
    public void verification(String uuid, HttpServletResponse response) throws IOException {  //验证码图片必须以输出流的形式输出图片的字节流返回，用串返回就不是图片了
        //可以直接在controller里注入httpServletResponse
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(299, 97);
        String code = lineCaptcha.getCode();
        redisTemplate.opsForValue().set("CODE:"+uuid,code,3, TimeUnit.MINUTES);//保存验证码3分钟
        //响应验证码图片，将图片数据写入到响应对象中,write就是把当前对象写入哪，此处是写入到输出流
        lineCaptcha.write( response.getOutputStream());

    }
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody Map map){
        String username = map.get("username").toString();
        String password = map.get("password").toString();
        String code = map.get("verificationCode").toString();
        String uuid = map.get("uuid").toString();
       Map token = adminService.login(username,password,code,uuid);
        return ResponseEntity.ok(token);
    }
    @PostMapping("/profile")
    public ResponseEntity profile(){
       AdminVo vo = adminService.profile();
       return ResponseEntity.ok(vo);
    }

}
